package com.lp.business.function;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.iframework.commons.util.HttpUtil;
import org.iframework.commons.util.fast.L;
import org.iframework.commons.util.fast.V;
import org.xml.sax.InputSource;

public class BaiduMapUtil {
	private static String AK = "gglV4DazMqOtp7RkYIPCXXIUClHbbabT";
	private static String URL = "http://api.map.baidu.com/geocoder/v2/";
	
	/**
	 * 调用百度api,通过地址获取经纬度信息
	 * @param position
	 * @return
	 */
	public static String getGIS(String position){
		String positionXY = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("address", position);
		params.put("output", "output");
		params.put("ak", AK);
		params.put("callback", "showLocation");
		try {
			String result = HttpUtil.get(URL, params);
			L.i("result:"+result);
			if(V.isEmpty(result)){
				return null;
			}
			//创建一个新的字符串
			StringReader read = new StringReader(result);
			//创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			//创建一个新的SAXBuilder
			SAXReader reader = new SAXReader();
			//通过输入源构造一个Document,获取docuemnt对象。
			Document document = reader.read(source);
            // 通过document对象获取根节点
            Element root = document.getRootElement();
            String lng = root.valueOf("//lng");
            String lat = root.valueOf("//lat");
            positionXY = lng+","+lat;
            L.i("positionXY:"+positionXY);
		} catch (DocumentException e) {
			L.e("调用百度api获取经纬度信息,文档解析失败");
			return null;
		}catch(Exception e){
			L.e("调用百度api获取经纬度信息失败");
			return null;
		}
		return positionXY;
	 
	}

	public static void main(String[] args) {
		String position = "北京市西城区";
		getGIS(position);
	}
	
}
